package org.socialresume.server;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.socialresume.client.model.FeedItem;
import org.socialresume.client.model.TwitterFeed;
import org.socialresume.client.model.action.GetUpdates;
import org.socialresume.client.model.action.GetUpdatesResult;

import net.customware.gwt.dispatch.server.ActionHandler;
import net.customware.gwt.dispatch.server.ExecutionContext;
import net.customware.gwt.dispatch.shared.ActionException;
import twitter4j.Paging;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;

public class GetUpdatesHandler implements ActionHandler<GetUpdates, GetUpdatesResult>{

	@Override
	public GetUpdatesResult execute(GetUpdates action, ExecutionContext arg1)
			throws ActionException {
		Twitter twitter = new Twitter();
		try {
			List<Status> status = null;
			if(action.getLastFeedId() != null){
				Paging paging = new Paging(action.getLastFeedId());
				status = twitter.getUserTimeline(action.getFeedLogin(),paging);
			}else{
				status = twitter.getUserTimeline(action.getFeedLogin());
			}
			List<FeedItem> items = new ArrayList<FeedItem>();
			for (Status status2 : status) {
				FeedItem item = new FeedItem(status2.getId()+"", status2.getCreatedAt(), status2.getText());
				Map<String,String> infos = new HashMap<String, String>();
				infos.put(TwitterFeed.TwitterFeedInfoEnum.PROFIL_LOGO_URL.getKey(),status2.getUser().getProfileImageURL().toString());
				item.setInfos(infos);
				items.add(item);
			}
			return new GetUpdatesResult(items);
		} catch (TwitterException e) {
			e.printStackTrace();
		}
		return new GetUpdatesResult(null);
	}

	@Override
	public Class<GetUpdates> getActionType() {
		return GetUpdates.class;
	}

	@Override
	public void rollback(GetUpdates arg0, GetUpdatesResult arg1,
			ExecutionContext arg2) throws ActionException {
		
	}

}
